<template>
  <div class="user-list">
    <div class="page-header">
      <div class="header-left">
        <h1>用户维护</h1>
        <p>管理系统用户信息</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showAddUserDialog = true">
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
      </div>
    </div>
    
    <!-- 搜索和筛选 -->
    <el-card class="filter-card" shadow="never">
      <el-row :gutter="16">
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-input
            v-model="searchQuery"
            placeholder="搜索用户名、邮箱..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-select v-model="statusFilter" placeholder="全部状态" clearable @change="handleFilter">
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-select v-model="authFilter" placeholder="认证状态" clearable @change="handleFilter">
            <el-option label="已认证" value="verified" />
            <el-option label="未认证" value="unverified" />
          </el-select>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-button @click="resetFilters">重置筛选</el-button>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 用户表格 -->
    <el-card class="table-card" shadow="hover">
      <el-table
        :data="paginatedUsers"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column label="用户信息" min-width="250">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="60" :src="row.avatar">
                {{ row.realName.charAt(0) }}
              </el-avatar>
              <div class="user-details">
                <h4>{{ row.username }}</h4>
                <p>{{ row.realName }}</p>
                <span class="user-id">ID: {{ row.id }}</span>
                <el-tag v-if="row.isOnline" type="success" size="small">在线</el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="联系方式" width="180">
          <template #default="{ row }">
            <div class="contact-info">
              <div class="email">{{ row.email }}</div>
              <div class="phone">{{ row.phone }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="认证状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.authStatus === 'verified' ? 'success' : 'warning'" size="small">
              {{ getAuthStatusText(row.authStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="注册时间" width="120" align="center">
          <template #default="{ row }">
            {{ formatDate(row.registerTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="最后登录" width="120" align="center">
          <template #default="{ row }">
            {{ formatDate(row.lastLoginTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="'active'"
              :inactive-value="'inactive'"
              @change="toggleUserStatus(row)"
              active-text="正常"
              inactive-text="禁用"
            />
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="viewUser(row)">
              查看
            </el-button>
            <el-button type="success" size="small" link @click="editUser(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" link @click="deleteUser(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredUsers.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 批量操作 -->
    <div v-if="selectedUsers.length > 0" class="batch-actions">
      <el-alert
        :title="`已选择 ${selectedUsers.length} 个用户`"
        type="info"
        show-icon
        closable
      >
        <template #default>
          <el-button type="success" size="small" @click="batchEnable">批量启用</el-button>
          <el-button type="warning" size="small" @click="batchDisable">批量禁用</el-button>
          <el-button type="danger" size="small" @click="batchDelete">批量删除</el-button>
        </template>
      </el-alert>
    </div>
    
    <!-- 新增用户对话框 -->
    <el-dialog
      v-model="showAddUserDialog"
      title="新增用户"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addUserFormRef"
        :model="addUserForm"
        :rules="addUserRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="addUserForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addUserForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="addUserForm.password" 
            type="password" 
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="addUserForm.confirmPassword" 
            type="password" 
            placeholder="请确认密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddUserDialog = false">取消</el-button>
          <el-button type="primary" @click="submitAddUser" :loading="addUserLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="showEditUserDialog"
      title="编辑用户"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editUserFormRef"
        :model="editUserForm"
        :rules="editUserRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserForm.username" disabled />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="editUserForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editUserForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editUserForm.status" placeholder="请选择状态">
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditUserDialog = false">取消</el-button>
          <el-button type="primary" @click="submitEditUser" :loading="editUserLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'

const loading = ref(false)
const searchQuery = ref('')
const statusFilter = ref('')
const authFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const selectedUsers = ref([])

// 对话框状态
const showAddUserDialog = ref(false)
const showEditUserDialog = ref(false)
const addUserLoading = ref(false)
const editUserLoading = ref(false)

// 表单引用
const addUserFormRef = ref()
const editUserFormRef = ref()

// 新增用户表单
const addUserForm = reactive({
  username: '',
  realName: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: ''
})

// 编辑用户表单
const editUserForm = reactive({
  id: '',
  username: '',
  realName: '',
  email: '',
  phone: '',
  status: 'active'
})

// 表单验证规则
const addUserRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== addUserForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const editUserRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
}

// 模拟用户数据
const users = ref([
  {
    id: 1,
    username: 'zhangsan',
    realName: '张三',
    email: 'zhangsan@example.com',
    phone: '13800138001',
    avatar: 'https://via.placeholder.com/60x60/667eea/ffffff?text=张',
    authStatus: 'verified',
    status: 'active',
    isOnline: true,
    registerTime: '2024-01-01',
    lastLoginTime: '2024-01-25 14:30:00'
  },
  {
    id: 2,
    username: 'lisi',
    realName: '李四',
    email: 'lisi@example.com',
    phone: '13800138002',
    avatar: 'https://via.placeholder.com/60x60/43e97b/ffffff?text=李',
    authStatus: 'verified',
    status: 'active',
    isOnline: false,
    registerTime: '2024-01-05',
    lastLoginTime: '2024-01-24 09:15:00'
  },
  {
    id: 3,
    username: 'wangwu',
    realName: '王五',
    email: 'wangwu@example.com',
    phone: '13800138003',
    avatar: 'https://via.placeholder.com/60x60/f093fb/ffffff?text=王',
    authStatus: 'unverified',
    status: 'active',
    isOnline: true,
    registerTime: '2024-01-10',
    lastLoginTime: '2024-01-25 16:45:00'
  },
  {
    id: 4,
    username: 'zhaoliu',
    realName: '赵六',
    email: 'zhaoliu@example.com',
    phone: '13800138004',
    avatar: 'https://via.placeholder.com/60x60/4facfe/ffffff?text=赵',
    authStatus: 'verified',
    status: 'inactive',
    isOnline: false,
    registerTime: '2024-01-15',
    lastLoginTime: '2024-01-20 11:20:00'
  },
  {
    id: 5,
    username: 'qianqi',
    realName: '钱七',
    email: 'qianqi@example.com',
    phone: '13800138005',
    avatar: 'https://via.placeholder.com/60x60/ff9a9e/ffffff?text=钱',
    authStatus: 'unverified',
    status: 'active',
    isOnline: false,
    registerTime: '2024-01-20',
    lastLoginTime: '2024-01-23 13:10:00'
  }
])

// 计算属性
const filteredUsers = computed(() => {
  let filtered = users.value
  
  if (searchQuery.value) {
    filtered = filtered.filter(user => 
      user.username.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      user.realName.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      user.email.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }
  
  if (statusFilter.value) {
    filtered = filtered.filter(user => user.status === statusFilter.value)
  }
  
  if (authFilter.value) {
    filtered = filtered.filter(user => user.authStatus === authFilter.value)
  }
  
  return filtered
})

const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredUsers.value.slice(start, end)
})

// 方法
const formatDate = (dateStr) => {
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

const getAuthStatusText = (status) => {
  return status === 'verified' ? '已认证' : '未认证'
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleFilter = () => {
  currentPage.value = 1
}

const resetFilters = () => {
  searchQuery.value = ''
  statusFilter.value = ''
  authFilter.value = ''
  currentPage.value = 1
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

const toggleUserStatus = (user) => {
  ElMessage.success(`用户 ${user.username} 状态已${user.status === 'active' ? '启用' : '禁用'}`)
}

const viewUser = (user) => {
  ElMessage.info(`查看用户：${user.username}`)
}

const editUser = (user) => {
  Object.assign(editUserForm, {
    id: user.id,
    username: user.username,
    realName: user.realName,
    email: user.email,
    phone: user.phone,
    status: user.status
  })
  showEditUserDialog.value = true
}

const deleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户"${user.username}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const index = users.value.findIndex(u => u.id === user.id)
    if (index > -1) {
      users.value.splice(index, 1)
      ElMessage.success('用户删除成功')
    }
  } catch {
    // 用户取消删除
  }
}

const submitAddUser = async () => {
  if (!addUserFormRef.value) return
  
  try {
    await addUserFormRef.value.validate()
    addUserLoading.value = true
    
    // 模拟API调用
    setTimeout(() => {
      const newId = Math.max(...users.value.map(u => u.id)) + 1
      const newUser = {
        id: newId,
        username: addUserForm.username,
        realName: addUserForm.realName,
        email: addUserForm.email,
        phone: addUserForm.phone,
        avatar: `https://via.placeholder.com/60x60/667eea/ffffff?text=${addUserForm.realName.charAt(0)}`,
        authStatus: 'unverified',
        status: 'active',
        isOnline: false,
        registerTime: new Date().toISOString().split('T')[0],
        lastLoginTime: new Date().toISOString().replace('T', ' ').split('.')[0]
      }
      
      users.value.push(newUser)
      showAddUserDialog.value = false
      
      // 重置表单
      Object.assign(addUserForm, {
        username: '',
        realName: '',
        email: '',
        phone: '',
        password: '',
        confirmPassword: ''
      })
      
      ElMessage.success('用户添加成功')
      addUserLoading.value = false
    }, 1000)
  } catch (error) {
    addUserLoading.value = false
  }
}

const submitEditUser = async () => {
  if (!editUserFormRef.value) return
  
  try {
    await editUserFormRef.value.validate()
    editUserLoading.value = true
    
    // 模拟API调用
    setTimeout(() => {
      const user = users.value.find(u => u.id === editUserForm.id)
      if (user) {
        Object.assign(user, {
          realName: editUserForm.realName,
          email: editUserForm.email,
          phone: editUserForm.phone,
          status: editUserForm.status
        })
      }
      
      showEditUserDialog.value = false
      ElMessage.success('用户信息更新成功')
      editUserLoading.value = false
    }, 1000)
  } catch (error) {
    editUserLoading.value = false
  }
}

const batchEnable = () => {
  selectedUsers.value.forEach(user => {
    user.status = 'active'
  })
  ElMessage.success(`批量启用 ${selectedUsers.value.length} 个用户`)
}

const batchDisable = () => {
  selectedUsers.value.forEach(user => {
    user.status = 'inactive'
  })
  ElMessage.success(`批量禁用 ${selectedUsers.value.length} 个用户`)
}

const batchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？此操作不可恢复。`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const ids = selectedUsers.value.map(u => u.id)
    users.value = users.value.filter(u => !ids.includes(u.id))
    selectedUsers.value = []
    ElMessage.success('批量删除成功')
  } catch {
    // 用户取消删除
  }
}

onMounted(() => {
  // 可以在这里调用API获取用户数据
  console.log('用户列表已加载')
})
</script>

<style scoped>
.user-list {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header-left h1 {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  margin-bottom: 4px;
}

.header-left p {
  color: #666;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 24px;
  border-radius: 12px;
}

.table-card {
  border-radius: 12px;
  margin-bottom: 24px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details h4 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 4px 0;
}

.user-details p {
  color: #666;
  font-size: 14px;
  margin: 0 0 4px 0;
}

.user-id {
  color: #999;
  font-size: 12px;
  margin-right: 8px;
}

.contact-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.email {
  color: #333;
  font-size: 14px;
}

.phone {
  color: #666;
  font-size: 12px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.batch-actions {
  margin-top: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #333;
  font-weight: 600;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: #f8f9fa;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-switch__label) {
  font-size: 12px;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .user-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .user-details p {
    max-width: none;
  }
}
</style> 